package com.tedu.eg06weibo.controller;

import com.tedu.eg06weibo.mapper.UserMapper;
import com.tedu.eg06weibo.pojo.dto.UserLoginDTO;
import com.tedu.eg06weibo.pojo.dto.UserRegDTO;
import com.tedu.eg06weibo.pojo.entity.User;
import com.tedu.eg06weibo.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @PostMapping("/v1/users/reg")
    public int reg(@RequestBody UserRegDTO userRegDTO) {
        System.out.println("开始处理注册");
        if (userMapper.selectByUsername(userRegDTO.getUsername())!=null){
            return 2;
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        userMapper.insert(user);
        return 1;
    }

    @PostMapping("/v1/users/login")
    public int login(@RequestBody UserLoginDTO userLoginDTO,HttpSession session){
        System.out.println("开始处理登录");
        User user = userMapper.selectByUsername(userLoginDTO.getUsername());
        if (user==null){
            return 3;
        }else if (!user.getPassword().equals(userLoginDTO.getPassword())){
            return 2;
        }
        session.setAttribute("user",user);
        return 1;
    }

    @GetMapping("v1/users/currentUser")
    public UserVO currentUser(HttpSession session){
        User user = (User) session.getAttribute("user");
        if (user==null){
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user,userVO);
        return userVO;
    }

    @GetMapping("v1/users/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }
}
